<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.2/fetch.min.js"></script>

<script>

function getIdTokenFromHash(url) {
  var match = url.match(/#.*id_token=([^&]+)(&|$)/);
  return(match ? match[1] : "");
}

function getUrlFromHash(url) {
  var match = url.match(/#.*state=([^&]+)(&|$)/);
  return(match ? match[1] : "");
}

console.log(window.location.hash);

var id_token = getIdTokenFromHash(window.location.hash);
var originalUrl = getUrlFromHash(window.location.hash);

console.log(id_token);
console.log(originalUrl);


var xhr;

if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xhr = new XMLHttpRequest();
} else {
      // code for IE6, IE5
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
}


xhr.open("POST", "/auth/token", true);
xhr.onreadystatechange = function() {
  console.log(xhr);
  if (xhr.readyState>3 && xhr.status==200) {
    console.log('here');
    // window.location = decodeURIComponent(originalUrl);
    window.location = xhr.responseURL || '/';
  }
};
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify({
  id_token: id_token,
  originalUrl: originalUrl,
}));

</script>
